import os
import json
import time
import requests
import threading


class MalodyCookieManager:
    def __init__(self, config_file='./plugins/malody/cookie.json'):
        self.config_file = config_file
        self.cookie = None
        self.last_update = 0
        self.keepalive_interval = 3600 * 6  # 每6小时保活一次
        self._keepalive_thread = None
        self._stop_event = threading.Event()
        self.load_config()

    def load_config(self):
        """加载本地 cookie"""
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    self.cookie = config.get('cookie', '')
                    self.last_update = config.get('last_update', 0)
                    print("[INFO] Cookie 加载成功")
            except Exception as e:
                print(f"[ERROR] 加载 cookie.json 失败: {e}")
                self.cookie = ''
        else:
            print("[WARN] 未找到 cookie.json，请手动登录后保存 Cookie。")
            self.cookie = ''

    def save_config(self):
        """保存 cookie 文件"""
        config = {
            'cookie': self.cookie,
            'last_update': self.last_update
        }
        os.makedirs(os.path.dirname(self.config_file), exist_ok=True)
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(config, f, ensure_ascii=False, indent=2)
            print("[INFO] Cookie 信息已保存。")
        except Exception as e:
            print(f"[ERROR] 保存 cookie.json 失败: {e}")

    def need_keepalive(self):
        """检查是否需要执行保活"""
        current_time = time.time()
        return current_time - self.last_update > self.keepalive_interval

    def keepalive(self):
        """使用当前 cookie 访问主页或个人页，防止 session 过期"""
        if not self.cookie:
            print("[WARN] 当前没有可用的 Cookie，无法保活。")
            return False

        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
            'Cookie': self.cookie,
            'Referer': 'https://m.mugzone.net/',
        }

        try:
            url = 'https://m.mugzone.net/account/profile/'
            response = requests.get(url, headers=headers, timeout=10)

            if response.status_code == 200:
                if "登录" in response.text or "login" in response.text.lower():
                    print("[WARN] Cookie 似乎已失效，需要手动更新。")
                    return False
                else:
                    self.last_update = time.time()
                    self.save_config()
                    print("[OK] Cookie 保活成功。")
                    return True
            else:
                print(f"[WARN] 保活请求返回状态码: {response.status_code}")
                return False
        except Exception as e:
            print(f"[ERROR] 保活请求失败: {e}")
            return False

    def run_keepalive_loop(self):
        """持续执行保活循环（阻塞调用）"""
        print("[INFO] 启动 Cookie 保活线程，每 6 小时执行一次。")
        while not self._stop_event.is_set():
            try:
                if self.need_keepalive():
                    print("[INFO] 正在执行 Cookie 保活...")
                    self.keepalive()
                else:
                    remain = int(self.keepalive_interval - (time.time() - self.last_update))
                    print(f"[INFO] 下次保活剩余 {remain // 60} 分钟。")
                # 每10分钟检查一次是否需要保活或停止
                self._stop_event.wait(600)
            except Exception as e:
                print(f"[ERROR] 保活循环异常: {e}")
                # 避免 tight loop on unexpected error
                time.sleep(60)

    def start_keepalive_thread(self):
        """在后台启动保活循环线程（非阻塞）"""
        if self._keepalive_thread and self._keepalive_thread.is_alive():
            print("[INFO] 保活线程已在运行。")
            return
        self._stop_event.clear()
        self._keepalive_thread = threading.Thread(target=self.run_keepalive_loop, daemon=True)
        self._keepalive_thread.start()
        print("[INFO] 已启动保活后台线程。")

    def stop_keepalive_thread(self):
        """停止后台保活线程"""
        if self._keepalive_thread and self._keepalive_thread.is_alive():
            self._stop_event.set()
            self._keepalive_thread.join(timeout=5)
            print("[INFO] 保活后台线程已停止。")

    def get_cookie(self, keepalive_if_needed=True):
        """
        返回当前 cookie 字符串。
        如果没有 cookie，会打印警告并返回空字符串。
        如果 keepalive_if_needed=True 且达到保活时间，会同步执行一次保活请求（不会自动登录）。
        """
        if not self.cookie:
            print("[WARN] 当前没有 cookie（请在 ./plugins/malody/cookie.json 中手动设置）")
            return ''

        if keepalive_if_needed and self.need_keepalive():
            print("[INFO] Cookie 需要保活，正在同步执行一次保活...")
            self.keepalive()

        return self.cookie

    def update_cookie_manually(self, new_cookie):
        """手动更新cookie并立即保存"""
        self.cookie = new_cookie
        self.last_update = time.time()
        self.save_config()
        print("[INFO] Cookie 手动更新成功")
